package gspringboot

import (
	"gitee.com/hongzhaomin/gspring"
	"gitee.com/hongzhaomin/gspring/iface"
	"gitee.com/hongzhaomin/hzm-common-go/easyconfig"
	"gitee.com/hongzhaomin/hzm-common-go/toolkit"
	"strconv"
	"xorm.io/xorm"
)

func propertiesWatcher(params []easyconfig.WatcherParam, _ map[easyconfig.ConfigurationBean]easyconfig.ConfigurationBeanDefinition) {
	logger := gspring.GetBeanByName[iface.GspringLogger](LoggerBeanName)
	environment := gspring.GetBeanByName[ConfigurationEnvironment](EnvironmentBeanName)
	for _, param := range params {
		k := param.Key
		oldVal := param.OldVal
		newVal := param.NewVal
		logger.Info("Gspring boot properties watched changed => key: [%s], oldValue: [%v], newValue: [%v]", k, oldVal, newVal)

		switch k {
		case logLevelPropName:
			logLevel, err := toolkit.ConvertStr4Any(newVal)
			if err != nil {
				logger.Error("Reset log level err: %v", err)
				break
			}
			logger.SetLogLevel(getLogLevelEnum(logLevel).getSlogLevel())
		case xormSqlShowPropName:
			if ok := environment.ContainsKey(dataSourceMysqlPropName); !ok {
				// 未开启xormplus，跳过
				break
			}
			isShowStr, err := toolkit.ConvertStr4Any(newVal)
			if err != nil {
				logger.Error("Reset xorm sql show err: %v", err)
				break
			}
			isShow, _ := strconv.ParseBool(isShowStr)
			engines := gspring.GetBeans[*xorm.Engine]()
			for _, engine := range engines {
				engine.ShowSQL(isShow)
			}
		}
	}
}
